package org.example.shoppingmall.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.shoppingmall.util.JWTUtil;
import org.example.shoppingmall.util.RedisUtil;
import org.example.shoppingmall.util.ResponseUtil;

import java.io.IOException;

@WebFilter("/*")
@MultipartConfig
public class JWTFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String path = httpRequest.getRequestURI();

        // 跳过注册和登录的路由
        if (path.equals("/user/register") || path.equals("/user/login")) {
            chain.doFilter(request, response);
            return;
        }

        String token = httpRequest.getHeader("Authorization");
        if (token != null) {
            if(token.startsWith("Bearer "))
                token = token.substring(7);

            // 验证 Token 是否有效
            if (!JWTUtil.isTokenExpired(token)) {
                Claims claims = JWTUtil.getClaimsFromToken(token);
                String userId = claims.get("userId", String.class);

                // 验证 Redis 中是否存在对应的 Token，以及获取的用户 ID 是否有效
                if (RedisUtil.get(token) != null && userId != null) {
                    // 检查当前请求的 Token 是否与 Redis 中存储的 Token 一致
                    String storedToken = RedisUtil.get(userId);
                    if (storedToken != null && storedToken.equals(token)) {
                        // 在请求属性中存储用户 ID，以便在后续处理中使用
                        httpRequest.setAttribute("userId", userId);

                        // 其他接口继续执行请求
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
        }

        // 如果 Token 验证失败，则返回 401 未授权状态码
        ResponseUtil.gen404Response(httpResponse, "游客请登录");
    }


    @Override
    public void destroy() {
    }
}

